package br.com.upper.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class JMeterProcessor {

	static JMeterRunnable jMeterRunnable;
	
	public static void process(String commandLine) {
		ExecutorService pool = Executors.newSingleThreadExecutor();
		jMeterRunnable = new JMeterRunnable(commandLine);
		pool.execute(jMeterRunnable);
		pool.shutdown();
	}
	
}

class JMeterRunnable implements Runnable {
	
	private String commandLine;
	
	StreamProcessor output;
	StreamProcessor error;
	
	boolean running;
	
	public JMeterRunnable(String commandLine) {
		this.commandLine = commandLine;
		running = true;
	}
	
	public void run() {
		try {
			Runtime rt = Runtime.getRuntime();
			Process proc = rt.exec(this.commandLine);
			
			// any error message?
			error = new 
				StreamProcessor(proc.getErrorStream(), "ERR");            
			
			// any output?
			output = new 
			StreamProcessor(proc.getInputStream(), "OUT");
			    
			// kick them off
			error.start();
			output.start();
			                        
			// any error???
			int exitVal = proc.waitFor();
			System.out.println("ExitValue: " + exitVal);
			
			if(exitVal == 0) {
				System.out.println("Teste concluido");
				running = false;
			} else {
				System.out.println("Processing Error: " + exitVal);
				running = false;
			}
			
		} catch (Throwable e) {
			System.out.println("Processing Error" +  e);
		}
	}
	
}

class StreamProcessor extends Thread {

	InputStream is;
	String type;
	OutputStream os;
	
	StringBuilder log;

	StreamProcessor(InputStream is, String type) {
		this(is, type, null);
	}

	StreamProcessor(InputStream is, String type, OutputStream redirect) {
		this.is = is;
		this.type = type;
		this.os = redirect;
		this.log = new StringBuilder();
	}
	
	public String getLogMessage() {		
		String retorno = this.log.toString();
		this.log = new StringBuilder();
		return retorno;		
	}

	public void run() {
		try {
			PrintWriter pw = null;
			if (os != null) {
				pw = new PrintWriter(os);
			}

			InputStreamReader isr = new InputStreamReader(is);
			BufferedReader br = new BufferedReader(isr);
			String line = null;
			while ((line = br.readLine()) != null) {
				if (pw != null) {
					pw.println(line);
				}
				System.out.println(type + ">" + line);
				this.log.append(line);
			}
			
			if (pw != null) {
				pw.flush();
			}
		} catch (IOException ioe) {
			System.out.println("Processing Error" + ioe);
		}
	}
}
